/**
 * Copyright 2019-2024 覃海林(qinhaisenlin@163.com).
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */ 

package com.qinhailin.pub.login.ctrl;


import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.qinhailin.common.base.BaseController;
import com.qinhailin.common.safe.TokenValidator;
import com.qinhailin.common.util.RsaUtil;
import com.qinhailin.portal.core.service.SysUserService;
import com.jfinal.aop.Before;
import com.jfinal.aop.Inject;
import com.jfinal.core.Path;
import com.jfinal.kit.Ret;
import com.qinhailin.pub.login.service.LoginService;

/**
 * 登陆
 * 
 * @author QinHaiLin
 * @date 2018-10-15
 */
@Path("/pub/login")
public class LoginController extends BaseController {

	@Inject
	LoginService loginService;
	@Inject
	SysUserService sysUserService;

	public void index() {
		createToken();
		setAttr("returnUrl",encodeReturnUrl(getPara("returnUrl","")));	
		render("login.html");
	}

	/**
	 * 登录认证
	 */
	@Before(TokenValidator.class)
	public void submit() {
		String userCode = getPara("userCode");
		String password = getPara("password");
		String returnUrl=encodeReturnUrl(getPara("returnUrl",""));
	
		try {
			password = RsaUtil.decryptByPrivateKey(password);
			password = URLDecoder.decode(password, "UTF-8");
			Ret ret=loginService.aopLogin(userCode, password, getRequest());
			if (ret.isOk()) {
				String sessionId = ret.getStr(LoginService.sessionIdName);
				int maxAgeInSeconds = ret.getInt("maxAgeInSeconds");
				setCookie(LoginService.sessionIdName, sessionId, maxAgeInSeconds, true);
				//登陆日志需要
				setSessionAttr("sessionId", sessionId);
			}
			redirect(!returnUrl.equals("")?returnUrl:"/");
		} catch (Exception e) {
			handerException(e);
			//显示验证码
			setAttr("vc", "verifyCode");
			setAttr("userCode",userCode);
			setAttr("password",password);
			setAttr("returnUrl", returnUrl);
			setAttr("msg", e.getCause()!=null?e.getCause().getMessage():e.getMessage());
			createToken();
			render("login.html");
		} 

	}
	
	/**
	 * 中文转码
	 * @param returnUrl
	 * @return
	 */
	private String encodeReturnUrl(String returnUrl){
		//匹配中文
		Pattern pattern=Pattern.compile("[\\u4e00-\\u9fa5]");
		Matcher matcher=pattern.matcher(returnUrl);		
		//中文转码
		while(matcher.find()){
			try {
				returnUrl=returnUrl.replace(matcher.group(), URLEncoder.encode(matcher.group(),"utf-8"));
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
		}
		return returnUrl;
	}
	
	/**
	 * 退出登录
	 */
	public void logout(){
		loginService.logout(getCookie(LoginService.sessionIdName));
		removeCookie(LoginService.sessionIdName);
		redirect("/pub/login");
	}
	
	/**
	 * 获取RSA公钥
	 */
	public void getPublicKey() {
		renderJson(ok(RsaUtil.getGenerateKeyPair().getPublicKey()));
	}
}
